import jwt
from django.conf import settings
from django.contrib.auth import get_user_model
from rest_framework.exceptions import AuthenticationFailed

User = get_user_model()

class JWTAuthenticationMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        excluded_paths = [
            '/api/user/login/',
            '/api/user/register/',
            '/api/user/logout/',
            '/api/user/verify-login/',
            '/api/user/profile/',
        ]
        if request.path in excluded_paths or request.user.is_authenticated:
            return self.get_response(request)
            
        token = request.COOKIES.get('jwt_token')
        if token:
            try:
                payload = jwt.decode(
                    token, 
                    settings.SECRET_KEY, 
                    algorithms=['HS256']
                )
                user = User.objects.get(id=payload['user_id'])
                request.user = user
            except jwt.ExpiredSignatureError:
                raise AuthenticationFailed('Token已过期')
            except jwt.InvalidTokenError:
                raise AuthenticationFailed('无效Token')
            except User.DoesNotExist:
                raise AuthenticationFailed('用户不存在')
                
        return self.get_response(request)